<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="unitName" placeholder="请输入单元名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="unitOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="单词名称" prop="wordName">
                <el-input v-model="queryParams.wordName" placeholder="请输入单词名称" clearable @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="单词含义" prop="wordMeaning">
                <el-input v-model="queryParams.wordMeaning" placeholder="请输入单词含义" clearable @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:word:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:word:remove']">删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['system:word:import']">导入单词</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:user:export']">导出</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="wordList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="单词名称" align="center" key="wordName" prop="wordName" />
              <el-table-column label="单词音节" align="center" key="wordVoiceName" prop="wordVoiceName" />
              <el-table-column label="单词音标" align="center" key="wordVoiceLabel" prop="wordVoiceLabel" />
              <el-table-column label="单词含义" align="center" key="wordMeaning" prop="wordMeaning" />
              <el-table-column label="所属单元" align="center" key="unitName" prop="unitName" />
              <el-table-column label="所属册本" align="center" key="courseName" prop="courseName" />
              <el-table-column label="所属教材" align="center" key="textbookName" prop="textbookName" />

              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:word:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['system:word:remove']"
                  >删除</el-button>
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="$download.resource(scope.row.wordAudioUrl,false)">下载音频</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改单词对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所在单元" prop="unitId">
          <treeselect v-model="form.unitId" :options="unitOptions" :disable-branch-nodes="true" :multiple="false" :show-count="true" placeholder="请选择所属单元" />
        </el-form-item>
        <el-form-item label="单词名称" prop="wordName">
          <el-input v-model="form.wordName" placeholder="请输入单词名称" />
        </el-form-item>
        <el-form-item label="单词音节" prop="remark">
          <el-input v-model="form.wordVoiceName" placeholder="请输入单词音节" />
        </el-form-item>
        <el-form-item label="单词音标" prop="remark">
          <el-input v-model="form.wordVoiceLabel" placeholder="请输入单词音标" />
        </el-form-item>
        <el-form-item label="单词含义" prop="remark">
          <el-input v-model="form.wordMeaning" placeholder="请输入单词含义" />
        </el-form-item>
        <el-form-item label="单词音频文件" prop="file">
          <file-upload v-model="form.wordAudioUrl"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 单词导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body>
      <el-form ref="upload" :model="upload" :rules="upload.rules" label-width="80px">
        <el-form-item label="Excel文件">
          <el-upload
            ref="fileUpload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWord, getWord, delWord, addWord, updateWord, unitTreeSelect } from "@/api/system/word";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import FileUpload from "@/components/FileUpload"
import "splitpanes/dist/splitpanes.css";
import { getToken } from "@/utils/auth";

export default {
  name: "word",
  dicts: ['sys_normal_disable'],
  components: { Treeselect, Splitpanes, Pane, FileUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单词表格数据
      wordList: null,
      // 所有单元树选项
      unitOptions: undefined,
      // 单元名称：用于树搜索
      unitName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 列信息
      columns: [
        { key: 0, label: `单词名称`, visible: true },
        { key: 1, label: `单词音节`, visible: true },
        { key: 2, label: `单词音标`, visible: true },
        { key: 3, label: `单词含义`, visible: true },
        { key: 4, label: `所属单元`, visible: true },
        { key: 4, label: `所属册本`, visible: true },
        { key: 4, label: `所属教材`, visible: true }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前选中的单词ID
      currentWordId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wordName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        wordName: [
          { required: true, message: "单词名称不能为空", trigger: "blur" }
        ]
      },
      // 导入参数
      upload: {
        open: false,
        title: "",
        isUploading: false,
        url: process.env.VUE_APP_BASE_API + "system/word/importData",
        courseType: undefined,
        headers: { Authorization: "Bearer " + getToken() },
        rules: {
          courseType: [
          ]
        }
      }
    };
  },
  created() {
    this.getList();
    this.getUnitTree();
  },
  methods: {
    /** 查询单词列表 */
    getList() {
      this.loading = true;
      listWord(this.queryParams).then(response => {
        this.wordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getUnitTree() {
      unitTreeSelect().then(response => {
        this.unitOptions = response.data;
        // this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
        console.log(this.unitOptions);
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.log('handleNodeClick---', data);
      this.queryParams.id = data.id;
      this.queryParams.lev = data.lev;
      this.handleQuery();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "单词导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.resetFields();
      this.$refs.fileUpload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.fileUpload.submit();
      this.upload.isUploading = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/word/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 提交按钮操作 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.wordId != undefined) {
            updateWord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const wordIds = row.wordId || this.ids;
      this.$modal.confirm('是否确认删除单词编号为"' + wordIds + '"的数据项？').then(function() {
        return delWord(wordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 取消按钮操作 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        wordId: undefined,
        wordName: undefined
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加单词";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const wordId = row.wordId || this.ids;
      getWord(wordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改单词";
      });
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.wordId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    }
  }
}

</script>
